package com.howtodoinjava.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.howtodoinjava.entity.User;
import com.howtodoinjava.security.CustomPasswordEncoder;
import com.howtodoinjava.security.MyUserContext;
import com.howtodoinjava.services.UserService;

@Controller
public class LoginController {

	@Autowired
	CustomPasswordEncoder passwordEncoder;

	@Autowired
	UserService userServices;

	@Autowired
	MyUserContext userContext;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String getAdmin(ModelMap model) {
		return "login";
	}

	@RequestMapping(value = "/login/form", method = RequestMethod.GET)
	public @ResponseBody String adminLogin(ModelMap model) {
		return "success";
	}

	@RequestMapping(value = "/signup", method = RequestMethod.GET)
	public String signUpPage(ModelMap model) {
		return "signup";
	}

	/**
	 * sign up new user 
	 * @param userName
	 * @param passWord
	 * @return
	 */
	@RequestMapping(value = "/signup/new", method = RequestMethod.POST)
	public String signUpNew(@RequestParam("userName") String userName,
			@RequestParam("password") String passWord) {
		String newPassword = passwordEncoder.encodePassword(passWord, userName);
		User user = new User(userName, newPassword, true, null);
		userServices.insertUser(user);
		userContext.setCurrentUser(user);

		return "redirect:/";
	}
}
